package org.ands.xml;

import java.io.InputStream;
import java.net.URL;

import javax.xml.namespace.NamespaceContext;

import org.w3c.dom.Document;

public class DOMHelperFromUri extends DOMHelper {

	/**
	 * Constructs a DOMHelper from and InputHelperUri.
	 *
	 * @param uri the uri
	 * @throws Exception the exception
	 * @since     	1.0
	 */
	public DOMHelperFromUri(final String uri) throws Exception{
		
		init(uri, null);
	}
	
	public DOMHelperFromUri(final String uri, final NamespaceContext nsContext) throws Exception {
		init(uri, nsContext);
	}
		
	
	private void init(final String uri, final NamespaceContext nsContext) throws Exception {
	
		if((uri == null) || (uri.isEmpty())){
			throw new Exception("Requires valid uri");
		}
		
		System.out.println("Constructing from uri "+uri);
		URL url = new URL(uri);
		_document = getDocumentFromInputStream(url.openStream());
		assert(_document != null);
		assert(_document.hasChildNodes());
		
		if(nsContext != null){
			_nsContext = nsContext;
		}
		else{
			_nsContext = new UniversalNamespaceResolver(_document);
		}
		
		assert(_nsContext != null);
	}
	
	/**
	 * Return Document.
	 * 
	 * @param inputStream
	 *            the input stream
	 * @return List of <code>String</code> value of element specified by xpath.
	 * @throws Exception
	 *             the exception
	 * @example Document document = getDocumentFromInputStream(new
	 *          FileInputStream(xmlFile));
	 * @example URL url = new URL(uri.getUri()); Document document =
	 *          DOMHelper.getDocumentFromInputStream(url.openStream());
	 * @see
	 * @since 1.0
	 */
	private Document getDocumentFromInputStream(
			final InputStream inputStream)
				throws Exception{
		
		if(inputStream == null){
			throw new Exception("Requires valid input stream");
		}
			
		try{
			Document doc = DOMHelper.documentBuilderInstance().parse(inputStream);
			doc.getDocumentElement().normalize();
	
			System.out.println("Returning Document with document element of [" + doc.getDocumentElement().getNodeName()+"] from inputStream.");
			assert(doc.getDocumentElement().hasChildNodes());
			return doc;
		}
		catch(Exception e){
			System.out.println("Parse failed.");
			e.printStackTrace();
			throw e;
		}
	}

	

}
